//
//  CardCenterViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/10.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

class CardCenterViewController: KMViewController {
    
    fileprivate let cellId = "cardCenterCell"
    fileprivate let cellId2 = "articleCell"
    
    var imageUrl = ""
    var titleText = ""
    
//    fileprivate var titleArray = ["",pinCard,late,bill] //标题数据
    fileprivate var dataArray = [CardCenterModel]() //卡片信息
//    fileprivate var pinCardArray = [ArticleModel]() //销卡信息
//    fileprivate var lateArray = [ArticleModel]() //账单
//    fileprivate var billArray = [ArticleModel]() //逾期

    
//    fileprivate var headView : CenterHeadView! //头部视图
    
//    fileprivate var footView : CenterFootView! //尾部视图
    
    fileprivate let bankView = SelectBankCenterView() //银行
    
    fileprivate var rightButton : UIBarButtonItem! //右键
    
//    fileprivate var moreButton : UIButton! //加载更多
    
    fileprivate var page = 1 //页数
    
    fileprivate var number : String! {//卡片数量
        didSet{
            self.title = self.titleText + cardCenter + "(" + number + "张)"
        }
    }
    
    
    fileprivate var tableView : UITableView!
    
    init(title:String,imageUrl:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.titleText = title
        self.title = title + cardCenter
        self.imageUrl = imageUrl
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createRightButton()
        createTableView()

//        getCardNews()
//        getArticleNews(type: pinCard) //销卡
//        getArticleNews(type: late) //逾期
//        getArticleNews(type: bill) //账单
        
        KMTool.setRefresh(with: self.tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getCardNews()
//            self?.getArticleNews(type: pinCard) //销卡
//            self?.getArticleNews(type: late) //逾期
//            self?.getArticleNews(type: bill) //账单
            
            }, footerAction: {[weak self] in
                
            self?.getCardNews()
                
        })
        
        tableView.mj_header.beginRefreshing()
        
    }
    
    //MARK: 创建导航栏右键
    fileprivate func createRightButton() {
        
        rightButton = UIBarButtonItem.init(image: UIImage.init(named: "xia"), style: .done, target: self, action: #selector(selectBankCard(sender:)))
        self.navigationItem.rightBarButtonItem = rightButton
    }
    
    //MARK: 选择银行信用卡
    @objc fileprivate func selectBankCard(sender:UIBarButtonItem) {
        
        if sender.image == UIImage.init(named: "xia") {
            sender.image = UIImage.init(named: "shang")
            bankView.isHidden = false
        }else{
            sender.image = UIImage.init(named: "xia")
            bankView.isHidden = true
        }
    }
    
    //MARK: 创建TableView
    fileprivate func createTableView() {
        
//        headView = CenterHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 80)))
//        headView.image = UIImage.imageWithName(self.imageUrl)
//        headView.title = self.titleText
        
//        footView = CenterFootView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 180)))
//        footView.centerDelegate = self
//        footView.articleView.text = self.titleText
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
//        tableView.sectionHeaderHeight = 0
//        tableView.contentInset = .init(top: -35, left: 0, bottom: 0, right: 0)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CardCenterCell.self, forCellReuseIdentifier: cellId)
//        tableView.register(ArticleCell.self, forCellReuseIdentifier: cellId2)
        self.view.addSubview(tableView)
        
        bankView.delegate = self
        bankView.isHidden = true
        self.view.addSubview(bankView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        bankView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
        
    }
    
    //MARK: 获取卡信息
    fileprivate func getCardNews(bank:String?=nil) {
        
        KMTool.requestMethod(.get, URLString: url_cardCenter, parameters: ["bank":bank ?? self.titleText,"p":self.page], success: { (value, json) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.page == 1 {
                self.dataArray.removeAll()
            }
            
            if let array = json["data"].arrayObject as? [[String:Any]] {
                
                if array.count == 0 {
//                    self.moreButton.setTitle(loadAll, for: .normal)
                    return
                }
                
                for item in array {
                    let model = CardCenterModel.setModel(with: item)
                    self.dataArray.append(model)
                }
                
                self.page += 1
                
//                self.headView.text = json["count_num"].stringValue
                self.number = json["count_num"].stringValue
//                self.moreButton.setTitle(viewMore, for: .normal)
                
                
//                self.tableView.reloadSections(NSIndexSet.init(index: 0) as IndexSet, with: .automatic) //刷新第一组数据
                self.tableView.reloadData()
            }
            
        }) {
            
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.endRefreshing()
        }
        
    }
    
    //MARK: 获取文章信息
    fileprivate func getArticleNews(type:String) {
        
        KMTool.requestMethod(.get, URLString: url_cardArticle, parameters: ["bank":self.titleText,"p":"1","cate":type], success: { (value, json) in
            
            self.tableView.mj_header.endRefreshing()
            
//            switch type {
//            case pinCard:
//                self.pinCardArray.removeAll()
//            case late:
//                self.lateArray.removeAll()
//            case bill:
//                self.billArray.removeAll()
//            default:
//                break
//            }
            
//            if let dic = json.dictionaryObject {
//
//                for i in 0...4{
//                    if let item = dic["\(i)"] as? [String:Any] {
//                        let model = ArticleModel.setModel(with: item)
//                        switch type {
//                        case pinCard:
//                            self.pinCardArray.append(model)
//                        case late:
//                            self.lateArray.append(model)
//                        case bill:
//                            self.billArray.append(model)
//                        default:
//                            break
//                        }
//
//                    }else{
//                        break
//                    }
//                }
//
//                switch type {
//                case pinCard:
//                    //刷新第2组
//                    self.tableView.reloadSections(NSIndexSet.init(index: 1) as IndexSet, with: .automatic)
//                case late:
//                    //刷新第3组
//                    self.tableView.reloadSections(NSIndexSet.init(index: 2) as IndexSet, with: .automatic)
//                case bill:
//                    //刷新第4组
//                    self.tableView.reloadSections(NSIndexSet.init(index: 3) as IndexSet, with: .automatic)
//                default:
//                    break
//                }
            
                
//            }
            
        }) {
            
            self.tableView.mj_header.endRefreshing()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        rightButton.image = UIImage.init(named: "xia")
        bankView.isHidden = true
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension CardCenterViewController : UITableViewDelegate,UITableViewDataSource {
    
//    func numberOfSections(in tableView: UITableView) -> Int {
//
//        return titleArray.count
//    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
//        switch section {
//        case 0:
            return dataArray.count
//        case 1:
//            return pinCardArray.count
//        case 2:
//            return lateArray.count
//        case 3:
//            return billArray.count
//        default:
//            return 0
//
//        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
//        if indexPath.section == 0 {
            return RATIO_H(maxNum: 140)
//        }else {
//            return RATIO_H(maxNum: 100)
//        }
        
    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//
//        if section == 0 {
//            return 0
//        }else{
//           return RATIO_H(maxNum: 40)
//        }
//
//    }
    
//    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//
//        if section == 0 {
//            return RATIO_H(maxNum: 30)
//        }else{
//            return 0
//        }
//    }
    
//    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//
//        if section == 0 {
//
//            moreButton = UIButton.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 30)))
//            moreButton.backgroundColor = UIColor.mineColor()
//            moreButton.setTitle(viewMore, for: .normal)
//            moreButton.setTitleColor(UIColor.black, for: .normal)
//            moreButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
//            moreButton.addTarget(self, action: #selector(loadMoreAction(sender:)), for: .touchUpInside)
//            return moreButton
//        }else{
//            return UIView()
//        }
//
//
//    }

//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
//        if section == 0 {
//            return UIView()
//        }else{
//            let heaView = CardTypeView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 40)))
//            heaView.text = self.titleText + creditCard + titleArray[section]
//            heaView.moreButton.tag = section
//            heaView.moreButton.addTarget(self, action: #selector(moreArticle(sender:)), for: .touchUpInside)
//            heaView.arrowImageView.addTarget(self, action: #selector(moreArticle(sender:)), for: .touchUpInside)
//            return heaView
//        }
//
//    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
//        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? CardCenterCell
            cell?.model = dataArray[indexPath.row]
            cell?.requestBtn.tag = indexPath.row
            cell?.requestBtn.addTarget(self, action: #selector(freeApplication(sender:)), for: .touchUpInside)
            return cell!
//        }else {
//            let cell = tableView.dequeueReusableCell(withIdentifier: cellId2, for: indexPath) as? ArticleCell
//            switch indexPath.section {
//            case 1:
//                cell?.model = pinCardArray[indexPath.row]
//            case 2:
//                cell?.model = lateArray[indexPath.row]
//            case 3:
//                cell?.model = billArray[indexPath.row]
//            default:
//                break
//            }
//            return cell!
//        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        var urlString  = ""
        var title = ""
        
        if indexPath.section == 0 {
            
            let model = dataArray[indexPath.row]
    
            urlString = webUrl + "/mobile/details/i" + model.id!
            title = model.credit_name!
            let webVC = WebViewController.init(urlString: urlString, title: title, shareImage: kmHttps + model.image!, shareText: model.favorable)
            self.navigationController?.pushViewController(webVC, animated: true)
            
        }else{
            
//            var text = ""
//            var shareTitle = ""
//
//            switch indexPath.section {
//            case 1:
//                urlString = "https://www.kameng98.com/posts/" + pinCardArray[indexPath.row].id!
//                text = pinCardArray[indexPath.row].posts_excerpt!
//                shareTitle = pinCardArray[indexPath.row].posts_title!
//            case 2:
//                urlString = "https://www.kameng98.com/posts/" + lateArray[indexPath.row].id!
//                text = lateArray[indexPath.row].posts_excerpt!
//                shareTitle = lateArray[indexPath.row].posts_title!
//            case 3:
//                urlString = "https://www.kameng98.com/posts/" + billArray[indexPath.row].id!
//                text = billArray[indexPath.row].posts_excerpt!
//                shareTitle = billArray[indexPath.row].posts_title!
//            default:
//                break
//            }
            
            
//            title = self.titleText + creditCard + titleArray[indexPath.section]
//            let webVC = WebViewController.init(urlString: urlString, title: title, shareImage: nil, shareText: text,shareTitle:shareTitle)
//            webVC.removeElements = ["mblock mblocks","crumbs mblock","mfooter mblock footer1"]
//            webVC.removeIds = ["xiong_div"]
//            self.navigationController?.pushViewController(webVC, animated: true)
        }
        
    }
    
    //MARK: 免费申请
    @objc fileprivate func freeApplication(sender:UIButton) {
        
        var urlString = ""
        
        let model = dataArray[sender.tag]
        if model.app_apply_access != "" {
            urlString = model.app_apply_access!
        }else if model.m_apply_access != "" {
            urlString = model.m_apply_access!
        }else if model.apply_access != "" {
            urlString  = model.apply_access!
        }
        
        
        if urlString == "" {
            return
        }
        
        KMTool.generateRecords(idString: model.id!)
        
        let webVC = WebDetailsViewController.init(urlString: urlString, title: dataArray[sender.tag].credit_name)
        self.navigationController?.pushViewController(webVC, animated: true)
    }
    
    //MARK: 加载更多
    @objc fileprivate func loadMoreAction(sender:UIButton) {
        
//        self.moreButton.setTitle(loadHard+"...", for: .normal)
        self.page += 1
        self.getCardNews()
    }
    
    //MARK: 查看更多文章
    @objc fileprivate func moreArticle(sender:UIButton) {
        
//        let articleVC = ArticleViewController.init(type: titleArray[sender.tag], title: self.titleText)
//        self.navigationController?.pushViewController(articleVC, animated: true)
    }
}


extension CardCenterViewController : CenterDelegate {
    
    //MARK: 选择信用卡类型
    func selectCardType(title: String) {
        
        let articleVC = ArticleViewController.init(type: title, title: self.titleText)
        self.navigationController?.pushViewController(articleVC, animated: true)
    }
    
    //MARK: 点击加载
    func touchLoad(title: String) {
        
//        var height:CGFloat = 0
//
//        if self.footView.centerView.frame.size.height > RATIO_H(maxNum: 300) {
//            height = RATIO_H(maxNum: 320)
//        }else{
//            height = 0
//        }
        
        if title == touchMore {
            
//            self.footView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 180))
            
            
        }else{
            
//            self.footView.frame = .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 340))
            
        }
        
        
        
        //self.tableView.tableFooterView = self.footView
        
    }
    
    //MARK: 选择信用卡类型
    func selectBankType(title: String,imageUrl:String) {
        
        self.titleText = title
        self.title = title + cardCenter
        self.page = 1
        //self.footView.articleView.text = self.titleText
        self.getCardNews(bank: title)
//        getArticleNews(type: pinCard) //销卡
//        getArticleNews(type: late) //逾期
//        getArticleNews(type: bill) //账单
        
    }
    

    
}

extension CardCenterViewController : SelectBankCenterViewDelegate {
    
    //MARK: 选择银行信用卡
    func selectBankCard(title: String) {
        
        self.titleText = title
        
        self.page = 1
        //self.footView.articleView.text = self.titleText
        self.getCardNews(bank: title)
//        getArticleNews(type: pinCard) //销卡
//        getArticleNews(type: late) //逾期
//        getArticleNews(type: bill) //账单
        
        rightButton.image = UIImage.init(named: "xia")
        bankView.isHidden = true
    }
}
